package org.yesin.auth.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.yesin.auth.utils.RsaUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@ConfigurationProperties(prefix = "yeshop.jwt")
public class JwtProperties {
    private String secret; //密钥
    private String pubKeyPath; //公钥路径
    private String priKeyPath; //私钥路径
    private int expire;  //过期时间
    private String cookieName;
    private PublicKey publicKey; //公钥
    private PrivateKey privateKey; //私钥

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtProperties.class);

    /**
     * @PostConstruct 在构造方法执行之后，执行该方法
     */
    @PostConstruct
    public void init(){
        try{

            File publicKey = new File(pubKeyPath);
            File privateKey = new File(priKeyPath);

            // 如果文件不存在，则创建，生成公钥和私钥
            if (!publicKey.exists() || !privateKey.exists()){
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }

            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);

        }catch (Exception e){
            LOGGER.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getPubKeyPath() {
        return pubKeyPath;
    }

    public void setPubKeyPath(String pubKeyPath) {
        this.pubKeyPath = pubKeyPath;
    }

    public String getPriKeyPath() {
        return priKeyPath;
    }

    public void setPriKeyPath(String priKeyPath) {
        this.priKeyPath = priKeyPath;
    }

    public int getExpire() {
        return expire;
    }

    public void setExpire(int expire) {
        this.expire = expire;
    }

    public String getCookieName() {
        return cookieName;
    }

    public void setCookieName(String cookieName) {
        this.cookieName = cookieName;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

}
